<?php

App::uses('AppController', 'Controller');

/**
 * CoreUsers Controller
 *
 * @property CoreUser $CoreUser
 */
class CoreUsersController extends AppController {

    static $iconCls = "user";

    /**
     * index method
     *
     * @return void
     */
    public function index() {
        $this->CoreUser->recursive = 0;
        $this->set('coreUsers', $this->paginate());
    }

    /**
     * view method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function view($id = null) {
        if (!$this->CoreUser->exists($id)) {
            throw new NotFoundException(__('Invalid core user'));
        }
        $options = array('conditions' => array('CoreUser.' . $this->CoreUser->primaryKey => $id));
        $this->set('coreUser', $this->CoreUser->find('first', $options));
    }

    /**
     * add method
     *
     * @return void
     */
    public function add() {
        if ($this->request->is('post')) {
            $this->CoreUser->create();
            if ($this->CoreUser->save($this->request->data)) {
                $this->Session->setFlash(__('The core user has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The core user could not be saved. Please, try again.'));
            }
        }
        App::import('Controller', 'CoreGroups');
        $coreGroups = new CoreGroupsController();
        $groups = $coreGroups->listGroupsFromDB();
        $this->set(compact('groups'));
    }

    /**
     * edit method
     *
     * @throws NotFoundException
     * @param string $id
     * @return void
     */
    public function edit($id = null) {
        if (!$this->CoreUser->exists($id)) {
            throw new NotFoundException(__('Invalid core user'));
        }
        if ($this->request->is('post') || $this->request->is('put')) {
            if (empty($this->request->data["CoreUser"]["cous_password"])) {
                unset($this->request->data["CoreUser"]["cous_password"]);
            }
            if ($this->CoreUser->save($this->request->data)) {
                App::import('Model', 'CoreUsersGroup');
                $coreUsersGroups = new CoreUsersGroup();
                $coreUsersGroups->create();
                // delete all modules for this block
                $data = array('CoreUsersGroup.core_users_id' => $id);
                // delete the data
                $coreUsersGroups->deleteAll($data);
                // save each module
                //var_dump($this->request->data);exit;
                if (!empty($this->request->data["CoreGroups"]["cogr_id"])) {
                    foreach ($this->request->data["CoreGroups"]["cogr_id"] as $value) {
                        $coreUsersGroups->create();
                        $data = array(
                            'CoreUsersGroup' => array(
                                'core_groups_id' => $value,
                                'core_users_id' => $id
                            )
                        );
                        // save the data
                        $coreUsersGroups->save($data);
                    }
                }
                $this->Session->setFlash(__('The core user has been saved'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('The core user could not be saved. Please, try again.'));
            }
        } else {
            $options = array('conditions' => array('CoreUser.' . $this->CoreUser->primaryKey => $id));
            $this->request->data = $this->CoreUser->find('first', $options);
        }

        App::import('Controller', 'CoreUsersGroups');
        $coreUsersGroup = new CoreUsersGroupsController();
        $selected = $coreUsersGroup->getGroupsIdFromUser($id);
        $this->set(compact('selected'));

        App::import('Controller', 'CoreGroups');
        $coreGroups = new CoreGroupsController();
        $groups = $coreGroups->listGroupsFromDB();
        $this->set(compact('groups'));
    }

    /**
     * delete method
     *
     * @throws NotFoundException
     * @throws MethodNotAllowedException
     * @param string $id
     * @return void
     */
    public function delete($id = null) {
        $this->CoreUser->id = $id;
        if (!$this->CoreUser->exists()) {
            throw new NotFoundException(__('Invalid core user'));
        }
        $this->request->onlyAllow('post', 'delete');
        if ($this->CoreUser->delete()) {
            $this->Session->setFlash(__('Core user deleted'));
            $this->redirect(array('action' => 'index'));
        }
        $this->Session->setFlash(__('Core user was not deleted'));
        $this->redirect(array('action' => 'index'));
    }

    static $block_login_iconCls = "key";

    public function block_login() {
        $this->set('isAuthorized', $this->isAuthorized());
        $this->set('isLogged', $this->isLogged());
    }

    static $block_login_small_iconCls = "key";

    public function block_login_small() {
        $this->set('isAuthorized', $this->isAuthorized());
        $this->set('isLogged', $this->isLogged());
    }

    public function login() {
        $this->layout = 'ajax';
        $this->response->type('json');
        if ($this->request->is('post')) {
            $coreSite = $this->Session->read('CoreSite');
            if ($coreSite["cosi_authentication_type"] == "Ldap") {
                // TODO verificar no site se o login é LDAP ou no sistema
                $ldapLogin = $this->ldapLogin($this->request->data('user'), $this->request->data('pass'));
                if ($ldapLogin) {
                    $this->CoreUser->setBypass(true);
                    $id = $this->createIfNotExists($this->request->data('user'), $this->request->data('pass'));
                    $this->CoreUser->setBypass(false);
                    $this->setGroupPermitionsFromUserId($id);
                }
            } else {
                $this->CoreUser->setBypass(true);
                $userData = $this->getUser($this->request->data('user'), $this->request->data('pass'));
                $this->CoreUser->setBypass(false);
                if (!empty($userData["CoreUser"]["id"])) {
                    $id = $userData["CoreUser"]["id"];
                    $this->setGroupPermitionsFromUserId($id);
                } else {
                    echo "false";
                    exit;
                }
            }

            //if ($this->Auth->login()) {
            if ($this->isAuthorized()) {
                //$this->redirect($this->Auth->redirect());
                $resp = "true";
            } else {
                //$this->Session->setFlash(__('Invalid username or password, try again'));
                $resp = "false";
            }
        }
        //$this->request->data('user')
        //Router::parseExtensions('json');
        echo $resp;
        exit;
    }

    public function setGroupPermitionsFromUserId($id) {
        App::import('Controller', 'CoreUsersGroups');
        $coreUsersGroupsController = new CoreUsersGroupsController();
        $coreUsersGroupsController->CoreUsersGroup->setBypass(true);
        $groups = $coreUsersGroupsController->getGroupsIdFromUser($id);
        $permitions = $coreUsersGroupsController->getModulesGroupsPermitionsFromUser($id);
        $coreUsersGroupsController->CoreUsersGroup->setBypass(false);
        $this->Session->write('user', array('id' => $id, 'groups' => $groups, 'cous_user' => $this->request->data('user'), 'permitions' => $permitions));

        // if the user has no permition set public permition for him
        App::import('Controller', 'CoreGroups');
        $coreGroups = new CoreGroupsController();
        $this->Session->write('userId', $id);
        $user = $this->Session->read('user');
        if (empty($user['permitions'])) {
            $this->Session->write('user', $coreGroups->getPublicPermitions($user));
        }
    }

    public function logout() {
        $this->Session->destroy();
        $this->redirect($this->Auth->logout());
    }

    function beforeFilter() {
        $this->Auth->allowedActions = array('login', 'logout');
        parent::beforeFilter();
    }

    private function ldapLogin($user, $pass) {
        $coreSite = $this->Session->read('CoreSite');
        if (!empty($coreSite["cosi_ldap_server"]) && !empty($coreSite["cosi_ldap_rdn"])) {
            // Variaveis Globais
            $ldap_server = $coreSite["cosi_ldap_server"]; /* Usamos o nome do dominio ou o nome do Servidor do dominio Casa seja 1 servidor Apenas */

            // Usuario para autenticacao na Base LDAP
            $auth_user = str_replace('{$user}', $user, $coreSite["cosi_ldap_rdn"]);
            //$auth_user = "uid={$user},ou=Users,dc=sextarm,dc=eb,dc=mil,dc=br"; /* nome Netbios\usuario */
            //$auth_user = "intranet6rm\\admin"; /* nome Netbios\usuario */
            $auth_pass = $pass; /* Senha do usuario do dominio */

            // Caminho LDAP do Dominio
            //$base_dn = "ou=Users,dc=sextarm,dc=eb,dc=mil,dc=br"; /* Nome do Dominio completo + OU principal */
            // Funcao para conectar na base LDAP e listas os usuarios de um grupo.
            if (($connect = ldap_connect($ldap_server))) {
                if (($bind = ldap_bind($connect, $auth_user, $auth_pass))) {
                    if ($bind === true) {
                        return true;
                    }
                }
            }
            // Fecha a conexao LDAP.
            //ldap_close($connect);
        }
        return false;
    }

    private function createIfNotExists($user, $pass) {
        $query = array(
            'conditions' => array('CoreUser.cous_user' => $user)
        );
        $userData = $this->CoreUser->find('first', $query);

        // prepare the model for adding a new entry
        $this->CoreUser->create();
        if (empty($userData["CoreUser"]["id"])) {
            $data = array(
                'CoreUser' => array(
                    'cous_user' => $user,
                    'cous_password' => $pass
                )
            );
            // save the data
            $this->CoreUser->save($data);

            return $this->CoreUser->getLastInsertID();
        } else {
            $data = array(
                'CoreUser' => array(
                    'id' => $userData["CoreUser"]["id"],
                    'cous_user' => $user,
                    'cous_password' => $pass
                )
            );

            // save the data
            $this->CoreUser->save($data);
            return $userData["CoreUser"]["id"];
        }
    }

    public function getUser($user, $pass) {
        $this->CoreUser->setBypass(true);
        $query = array(
            'conditions' => array('CoreUser.cous_user' => $user, 'CoreUser.cous_password' => $pass)
        );
        $userData = $this->CoreUser->find('first', $query);
        $this->CoreUser->setBypass(false);
        return $userData;
    }

}
